package org.robot.scm.platform.server.handler.archery;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.net.HttpCookie;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.server.handler.BaseHandler;
import org.robot.scm.pojos.archery.DetailResponse;
import org.robot.scm.pojos.archery.DetailRows;
import org.robot.scm.utils.JsonHelper;

@Slf4j
@NoArgsConstructor
public class ArcheryDetailHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/archery/getById";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        Map<String, String> query = queryToMap(exchange.getRequestURI().getQuery());
        String workflowId = query.get("workflowId");
        List<DetailRows> detailRows = this.getById(workflowId);
        sendSuccessResponse(exchange, "查询成功", JsonHelper.toJSONString(detailRows));
    }

    private List<DetailRows> getById(String workflowId) {
        String token = RedisCacheHelper.get("archery_token");
        String sessionId = RedisCacheHelper.get("archery_session");

        String detailUrl = ArcheryConfig.ARCHERY_URL + "/sqlworkflow/detail_content/?workflow_id=" + workflowId;
        HttpResponse response = HttpUtil.createRequest(Method.GET, detailUrl)
                .cookie(new HttpCookie("csrftoken", token), new HttpCookie("sessionid", sessionId))
                .execute();
        String result = response.body();
        if (StringUtils.contains(result, "CSRF验证失败") || StringUtils.isBlank(result)) {
            ArcheryHelper.loginAndSession();
            return getById(workflowId);
        }

        DetailResponse detailResponse = JsonHelper.toObject(response.body(), DetailResponse.class);
        detailResponse.getRows().sort(Comparator.comparingInt(DetailRows::getId));
        return detailResponse.getRows();
    }
}
